const assert = require('http-assert')
const jwt = require('jsonwebtoken')
const keys = require('../config/keys')
const User = require('../model/UserModel')
const R = require('../config/R')

exports.getUserFromHeader = async (req) => {
  const authorization = req.headers.authorization

  // bear token 不存在
  assert(authorization, 400, R.NOT_EXIST_TOKEN)

  // 格式错误
  const bearer = authorization.startsWith('Bearer ')
  assert(bearer, 400, R.INVALID_TOKEN)

  // 格式错误
  const token = authorization.substr(7)
  assert(token, 400, R.INVALID_TOKEN)

  // 校验 token
  const payload = jwt.verify(
    token,
    keys.secretOrKey,
    {
      ignoreExpiration: false,
      ignoreNotBefore: false
    },
    (error, decoded) => {
      if (error) {
        console.log(error.message)
        return
      }
      return decoded
    }
  )

  // token 解析失败
  assert(payload, 400, R.TOKEN_EXPIRED)

  const { name } = payload
  // 用户名不存在
  assert(name, 400, R.INVALID_TOKEN)

  // 查找用户
  const user = await User.findOne({ name: name })
  // 用户不存在
  assert(user, 400, R.USER_NOT_EXIST)

  return user
}
